<template>
  <a-modal
    :title="title"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :okButtonProps="{ props: {disabled: disabled} }"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="msgCategory" label="消息类型">
          <a-radio-group v-model="model.msgCategory" @change="selectMsgCategory" :disabled="disableSubmit">
            <a-radio value="1" v-show="isAdmin&&(messageType==''||messageType=='1')">通知公告</a-radio>
            <a-radio value="2" v-show="isAdmin&&messageType===''||messageType==='2'">系统消息</a-radio>
            <a-radio value="3" v-show="messageType==''||messageType==='3'">反馈消息</a-radio>
            <a-radio value="4" v-show="messageType===''||messageType==='4'">报警消息</a-radio>
            <a-radio value="5" v-show="messageType===''||messageType==='5'">人机对话</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item v-if="model.msgCategory && model.msgCategory=='3'" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectCode" label="项目代号">
          <!-- <a-input placeholder="请输入项目代号" v-model="model.projectCode"  @change="selectProject" :readOnly="disableSubmit"/> -->
          <a-select v-model="model.projectCode"  @change="selectProject" :readOnly="disableSubmit">
            <a-select-option v-for="item in projects" :key="item.equipmentProjectcode" :value="item.equipmentProjectcode">{{item.equipmentProjectcode}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item v-if="false" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="toUsername" label="接收人">
          <!-- <a-input placeholder="请输入反馈接收人" v-model="model.toUsername" :readOnly="disableSubmit"/> v-if="model.msgCategory && model.msgCategory=='3'"-->
                <j-popup 
                :readOnly="true"
                placeholder="请输入反馈接收人" 
                v-model="model.toUsername"
                field="toUsername"
                org-fields="user_name,user_id"
                dest-fields="toUsername,toUserIds"
                code="projectUserQuery"
                :param="popParam"
                :multi="false"
                @input="popupCallback"
                :keys="model.toUserIds"
                key-field="user_id"
                />
        </a-form-model-item>
        <a-form-model-item v-if="model.msgCategory && model.msgCategory=='3'" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="replyType" label="反馈类型">
          <!-- <a-input placeholder="请输入反馈类型" v-model="model.toUserIds" :readOnly="disableSubmit"/> -->
             <j-dict-select-tag type="list" v-model="model.replyType" dictCode="reply_type" placeholder="请选择反馈类型" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="titile" label="标题">
          <a-input placeholder="请输入标题" v-model="model.titile" :readOnly="disableSubmit"/>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="msgAbstract" label="摘要">
          <a-textarea placeholder="请输入摘要"  v-model="model.msgAbstract" />
        </a-form-model-item>
        <!-- <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endTime" label="截至日期" class="endTime">
          <j-date style="width: 100%" :getCalendarContainer="node => node.parentNode" v-model="model.endTime" placeholder="请选择结束时间" showTime dateFormat="YYYY-MM-DD HH:mm:ss" />
        </a-form-model-item> -->
        <a-form-model-item v-if="model.msgCategory && model.msgCategory!='3'" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="msgType" label="接收用户">
          <a-radio-group v-model="model.msgType" :disabled="disableSubmit" @change="chooseMsgType">
            <a-radio value="USER" >指定用户</a-radio>
            <a-radio value="ALL" >全体用户</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="指定用户" v-if="userType&&model.msgCategory!='3'">
          <j-popup 
                :readOnly="true"
                placeholder="请选择指定用户" 
                v-model="model.toUsersnames"
                field="toUsersnames"
                org-fields="user_name,user_id"
                dest-fields="toUsersnames,toUsersIds"
                code="projectUserQuery"
                :param="popParam"
                :multi="true"
                @input="popupCallback"
                :keys="model.toUsersIds"
                key-field="user_id"
                />
          <!-- <j-select-multi-user :returnKeys="returnKeys" placeholder="请选择指定用户" v-model="userIds"  :trigger-change="true"></j-select-multi-user>  -->
          <!-- filterField="username" :userIds="equipmentUserIds" -->
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优先级" >
          <a-radio-group v-model="model.priority" placeholder="请选择优先级" :disabled="disableSubmit">
            <a-radio value="L">低</a-radio>
            <a-radio value="M">中</a-radio>
            <a-radio value="H">高</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelColX1" :wrapperCol="wrapperColX1" label="内容" class="j-field-content">
          <j-editor v-model="model.msgContent" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { getAction } from '@/api/manage'
  import JDate from '@/components/jeecg/JDate'
  import JEditor from '@/components/jeecg/JEditor'
  import SelectUserListModal from "./SelectUserListModal";
  import moment from 'moment'
  import JPopup from '@/components/jeecg/JPopup.vue'
  import { USER_NAME,USER_INFO} from "@/store/mutation-types"
    import Vue from 'vue'

  export default {
    components: { JEditor, JDate, 
    SelectUserListModal,
    JPopup},
    name: "SysAnnouncementModal",
    data () {
      return {
        title:"操作",
        visible: false,
        disableSubmit:false,
        model: {
          toUserIds:'',
          toUsername:'',
          toUsersIds:'',
          toUsersnames:'',
        },
        popParam:{user_class:'1',project_code:'牛钮'},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 },
        },
        labelColX1: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperColX1: {
          xs: { span: 24 },
          sm: { span: 18 },
        },
        confirmLoading: false,
        validatorRules:{
          titile: [{ required: true, message: '请输入标题!' }],
          msgCategory: [{ required: true, message: '请选择消息类型!' }],
          msgType:[{ required: true, message: '请选择通告对象类型!' }],
          endTime:[{ required: true, message: '请选择结束时间!'} ,{validator: this.endTimeValidate}],
          startTime:[{required: true, message: '请选择开始时间!'},{validator: this.startTimeValidate}],
          msgAbstract: [{ required: true, message: '请输入摘要!' }],
          replyType:[{ required: true, message: '请反馈类型!' }]
        },
        url: {
          queryByIds: "/sys/user/queryByIds",
          add: "/sys/annountCement/add",
          edit: "/sys/annountCement/edit",
          queryRoles:"/sys/user/queryUserRole",
          list: "/mng/yksEquipmentManageUsers/list",
        },
        projects:[],
        userinfo : null,
        userType:false,
        userIds:"",
        selectedUser:[],
        disabled:false,
        msgContent:"",
        replyOprationFLag : false,
        userList:[],
        returnKeys:['id', 'id'], //用户选择返回字段
        equipmentUserIds:['ykadmin'],
        roles:[],
        isAdmin:true,
        messageType:''
      }
    },
    created () {
      this.userinfo = Vue.ls.get(USER_INFO);
      this.getProjectCode()
      // this.popParam =  {user_class:'1',user_name:this.userinfo.username},
      console.log(this.userinfo)
      this.getUserRoles()
      if(this.messageType!=''){
        this.msgCategory=this.messageType
      }
    },
    methods: {
      getProjectCode(){
          getAction('/dev/yksEquipment/list', {
            pageNo: 1,
            pageSize: 100,
          }).then((res) => {
            this.projects = res.result.records
            console.log(res.result.records)
          })

      },
      getUserRoles(){
        getAction(this.url.queryRoles, {
          userid: this.userinfo.id
          }).then((res) => {
            this.roles = res.result
            if(this.roles.indexOf("1727146690145206274")<0&&this.roles.indexOf("f6817f48af4fb3af11b9e8bf182f618b")<0&&this.roles.indexOf("1751140588584558593")<0){
              this.isAdmin=false
            }
            console.log(res.result.records)
          })
      },
      popupCallback(value,row){
        debugger
         this.model = Object.assign(this.model, row);

         debugger
      },
      selectMsgCategory(type){
        console.log(type.target.value)
          if (type.target.value=='3') {
            this.model.msgType = 'USER'
            this.userType = true
          }
      },
      selectProject(text) {
        this.popParam.project_code = text;
        if(text&&text!=''){
          this.loadProjectUsersData();
        }
      },
      add () {
        this.edit({});
      },
      edit (record) {
        this.model = {}
        if(!record.endTime||record.endTime==''){
          record.endTime="2099-12-31 00:00:00"
        }
        this.disable = false;
        this.visible = true;
        this.getUser(record);
      },
      getUser(record){
        //update-begin---author:wangshuai ---date:20211227  for：[JTC-191]系统通告参考vue3的来改，为单选按钮附默认值------------
        record.msgCategory = record.msgCategory?record.msgCategory:(this.messageType==''?"1":this.messageType)
        record.msgType = record.msgType?record.msgType:"ALL"
        record.priority = record.priority?record.priority:"H"
        //update-begin---author:wangshuai ---date:20211227  for：[JTC-191]系统通告参考vue3的来改，为单选按钮附默认值------------
        this.model = Object.assign({}, record);
        if(this.messageType=="3"){
          this.model.msgType = 'USER'
            this.userType = true
        }
        // 指定用户
        if(record&&record.msgType === "USER"){
          this.userType =  true;
          this.selectProject(record.projectCode)
          this.model.userIds=record.userIds.substr(0,record.userIds.length-1);
          
          // this.model.toUserIds=this.model.toUserIds+','
          this.model.toUsersIds=record.userIds.replace(this.model.toUserIds+",",'') 
          debugger
          if(this.model.toUsersIds.endsWith(',')){
            this.model.toUsersIds=this.model.toUsersIds.slice(0, -1);
          }
          //update-begin---author:wangshuai ---date:20220104  for：[JTC-304]指定人员不支持分页勾选,换通用的用户组件------------
          // this.userIds = record.userIds.substr(0,record.userIds.length-1);
          //update-end---author:wangshuai ---date:20220104  for：[JTC-304]指定人员不支持分页勾选,换通用的用户组件------------
        }
      },
      close () {
        this.$emit('close');
        this.selectedUser = [];
        this.visible = false;
        this.$refs.form.resetFields();
      },
      loadProjectUsersData() {
        
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        // if (arg === 1) {
        //   this.ipagination.current = 1;
        // }
        // var params = this.getQueryParams();//查询条件
        let project=this.projects.find(p => p.equipmentProjectcode === this.model.projectCode)
        if(!project)return
        var params={}
        params.equipmentId = project.id
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            let list = res.result.records||res.result;
            this.model.toUsersIds=''
            if(list.length>0){
              for(var i=0;i<list.length;i++){
                debugger
                this.model.toUsersIds=this.model.toUsersIds+list[i].userId+","
              }
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }else{
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loading = false
        })
      },
      handleOk () {
        const that = this;
        if(this.messageType=="3"){
          if(this.model.projectCode&&this.model.projectCode!=''){
            this.loadProjectUsersData();
          }else{
            this.$message.warning('请选择项目代号！')
            return;
          }
          
        }
        //当设置指定用户类型，但用户为空时，后台报错
        if(this.userType &&!(this.model.toUsersIds!=null && this.model.toUsersIds.length >0)){
            this.$message.warning('指定用户不能为空！')
            return;
          }
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            if(this.userType){
              debugger
              //update-begin---author:wangshuai ---date:20220104  for：[JTC-304]指定人员不支持分页勾选,换通用的用户组件------------
              this.model.userIds =  this.model.toUsersIds;
              // if(this.model.toUserIds.endsWith(',')){
              //   this.model.toUserIds=this.model.toUserIds.slice(0, -1);
              // }
              //update-end---author:wangshuai ---date:20220104  for：[JTC-304]指定人员不支持分页勾选,换通用的用户组件------------
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
                that.resetUser();
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })

          }else{
            return false;
          }
        })
      },
      handleCancel () {
        this.visible = false;
        this.$emit('close');
        this.$refs.form.resetFields();
        this.resetUser();
      },
      resetUser (){
        this.userType =  false;
        //update-begin---author:wangshuai ---date:20220318  for：[issues/I4X63V]vue有些页面报错，但是在线演示的却没有-----
        this.userIds ="";
        //update-end---author:wangshuai ---date:20220318  for：[issues/I4X63V]vue有些页面报错，但是在线演示的却没有-----
        this.disabled = false;
      },
      chooseMsgType(e) {
        if("USER" == e.target.value) {
          this.userType = true;
        } else {
          this.userType = false;
          //update-begin---author:wangshuai ---date:20220318  for：[issues/I4X63V]vue有些页面报错，但是在线演示的却没有-----
          this.userIds = "";
          //update-end---author:wangshuai ---date:20220318  for：[issues/I4X63V]vue有些页面报错，但是在线演示的却没有-----
        }
      },
      startTimeValidate(rule,value,callback){
        let endTime = this.model.endTime
        if(!value || !endTime){
          callback()
        }else if(moment(value).isBefore(endTime)){
          callback()
        }else{
          callback("开始时间需小于结束时间")
        }
      },
      endTimeValidate(rule,value,callback){
        let startTime = this.model.startTime;
        if(!value || !startTime){
          callback()
        }else if(moment(startTime).isBefore(value)){
          callback()
        }else{
          callback("结束时间需大于开始时间")
        }
      },
    }
  }
</script>

<style scoped>

</style>